<?php
class base {
	private $kv;
	private $config;
	private $fid;
	public function __construct () {
		$this->init();
	}
	public function init () {
		$this->kv=new SaeKV();
		$this->kv->init();
	}
	public function db ($type,$key,$val='',$is_json=TRUE) {
		if ($type=='get') {
			if ($is_json) return jd($this->kv->get(DBPRE.$key));
			else return $this->kv->get(DBPRE.$key);
		} elseif ($type=='set') {
			if ($is_json && is_array($val)) return $this->kv->set(DBPRE.$key,json_encode($val));
			else return $this->kv->set(DBPRE.$key,$val);
		}
	}
	public function init_config ($re=FALSE) {
		if (is_array($this->config) && !$re) return;
		$cfg=$this->db('get','config');
		if (!is_array($cfg)) $cfg=array();
		$this->config=$cfg;
	}
	public function getval ($name) {
		$this->init_config();
		if (isset($this->config[$name])) return $this->config[$name];
		else return NULL;
	}
	public function setval ($name,$val) {
		$this->init_config();
		if ($val!==NULL) $this->config[$name]=$val;
		elseif (isset($this->config[$name])) unset($this->config[$name]);
		else return TRUE;
		$this->db('set','config',$this->config);
	}
	public function get_tbinfo ($kw) {
		$data=array(
			'from'=>'tieba',
			'kw'=>$kw,
			'pn'=>'1',
			'q_type'=>'2',
			'rn'=>'30',
			'with_group'=>'1'
		);
		$data=array_merge(client_mkClient_post1(FALSE),$data);
		$sign=client_sign($data);
		$data['sign']=$sign;
		$url=$this->mkurl('c/f/frs/page','c');
		$info_json=curl_get($url,array('post'=>$data));
		$info=jd($info_json);
		return $info;
	}
	public function get_tbs (){
		static $tbs='';
		if (!empty($tbs)) return $tbs;
		$url=$this->mkurl('dc/common/tbs');
		$tbs_json=curl_get($url);
		$tbsaaa=jd($tbs_json);
		$tbs=$tbsaaa['tbs'];
		return $tbs;
	}
	public function get_cookie () {
		return 'BDUSS='.$this->get_bduss();
	}
	public function get_fid ($tieba) {
		$tbkey=md5($tieba);
		if (!is_array($this->fid)) $this->fid=$this->db('get','fid');
		if (!is_array($this->fid)) $this->fid=array();
		if (isset($fid[$tbkey])) return $fid[$tbkey];
		$info=$this->get_tbinfo($tieba);
		$id=$info['forum']['id'];
		if (empty($id)) $this->DisplayError('无法获取该贴吧的fid');
		$this->fid[$tbkey]=$id;
		$this->db('set','fid',$this->fid);
		return $id;
	}
	public function is_login (){
		static $is_login=NULL;
		if (is_bool($is_login)) return $is_login;
		$url=$this->mkurl('dc/common/tbs');
		$check=jd(curl_get($url));
		$is_login=($check['is_login']!=1)?FALSE:TRUE;
		return $is_login;
	}
	public function ShowTips ($info,$type) {
		if (defined('CRON')) exit('CRON');
		include(TPL.'head.html');
		echo '<div class="alert alert-',$type,'">',$info,'</div>';
		include(TPL.'footer.html');
	}
	public function mkurl ($dir,$qian='') {
		$tburl='tieba.baidu.com';
		$r='http://';
		if (!empty($qian)) $r.=$qian.'.';
		$r.=$tburl.'/'.$dir;
		return $r;
	}
	public function DisplayError ($info) {
		$this->ShowTips($info,'warning');
		exit;
	}
	public function get_bduss () {
		return $this->getval('BDUSS');
	}
}
?>